package com.enation.app.web.core.action.api;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.enation.app.base.core.action.api.ValidCodeApiController;
import com.enation.app.web.core.model.Member;
import com.enation.app.web.core.service.IMemberManager;
import com.enation.framework.action.JsonResult;
import com.enation.framework.context.webcontext.ThreadContextHolder;
import com.enation.framework.context.webcontext.WebSessionContext;
import com.enation.framework.util.JsonResultUtil;
import com.enation.framework.util.JsonUtil;
import com.enation.framework.util.StringUtil;

/**
 * 
 * @function 成员API
 * @author 闯哥
 * @time 2016年11月30日 下午10:45:52
 */
@Controller
@RequestMapping("/api/member")
public class MemberController {

	@Autowired
	private IMemberManager memberManager;

	/**
	 * 
	 * @function 注册
	 * @param student_number
	 *            ----学号
	 * @param password
	 *            ----密码
	 * @param rePassword
	 *            ----重复密码
	 * @param checkCode
	 *            ----验证码
	 * @param real_name
	 *            ----真实姓名
	 * @param nick_name
	 *            ----昵称
	 * @return :消息
	 */
	@ResponseBody
	@RequestMapping(value = "/register")
	public JsonResult register(String student_number, String password,
			String rePassword, String checkCode, String real_name,
			String nick_name) {

		// 验证字段
		if (checkCode == null) {
			return JsonResultUtil.getErrorJson("验证码没有输入！");

		}
		if (checkCode.equals("")) {
			return JsonResultUtil.getErrorJson("请求错误！验证码没有填写！");
		}
		if (checkCode.length() != 4) {
			return JsonResultUtil.getErrorJson("请求错误！验证码错误！");
		}

		// 验证验证码是否正确
		checkCode = checkCode.toLowerCase();
		WebSessionContext sessonContext = ThreadContextHolder
				.getSessionContext();
		Object realCode = ("" + sessonContext
				.getAttribute(ValidCodeApiController.SESSION_VALID_CODE
						+ "admin")).toLowerCase();

		if (!checkCode.equals(realCode)) {
			return JsonResultUtil.getErrorJson("验证码输入错误");

		}

		if (student_number == null) {
			return JsonResultUtil.getErrorJson("请求错误！学号没有填写！");
		}
		if (student_number.equals("")) {
			return JsonResultUtil.getErrorJson("请求错误！学号没有填写！");
		}
		if (password == null) {
			return JsonResultUtil.getErrorJson("请求错误！密码没有填写！");
		}
		if (password.equals("")) {
			return JsonResultUtil.getErrorJson("请求错误！密码没有填写！");
		}
		if (rePassword == null) {
			return JsonResultUtil.getErrorJson("请求错误！密码没有填写！");
		}
		if (rePassword.equals("")) {
			return JsonResultUtil.getErrorJson("请求错误！密码没有填写！");
		}
		if (real_name == null) {
			return JsonResultUtil.getErrorJson("请求错误！姓名没有填写！");
		}
		if (real_name.equals("")) {
			return JsonResultUtil.getErrorJson("请求错误！姓名没有填写！");
		}
		if (nick_name == null) {
			return JsonResultUtil.getErrorJson("请求错误！昵称没有填写！");
		}
		if (nick_name.equals("")) {
			return JsonResultUtil.getErrorJson("请求错误！昵称没有填写！");
		}

		// 学号验证
		student_number = student_number.toUpperCase();
		if (!student_number.startsWith("P1")) {
			return JsonResultUtil.getErrorJson("请求错误！学号填写错误！");
		}
		if (student_number.length() != 10) {
			return JsonResultUtil.getErrorJson("请求错误！学号填写错误！");
		}

		// 判断密码是否符合规则
		if (password.length() < 6 || password.length() > 12) {
			return JsonResultUtil.getErrorJson("请求错误！密码填写不争取！");
		}

		// 判断两次密码是否一致
		if (!password.equals(rePassword)) {
			return JsonResultUtil.getErrorJson("请求错误!密码错误！");

		}

		// 查询是否注册过
		int flag = this.memberManager.checkIsRegister(student_number);
		if (flag == 1) {
			return JsonResultUtil.getErrorJson("该学号已经注册过了！");
		}

		// 查询昵称是否使用过
		flag = this.memberManager.checkNickName(nick_name);
		if (flag == 1) {
			return JsonResultUtil.getErrorJson("该昵称已经注册过了！");
		}

		Member member = new Member();
		member.setStudent_number(student_number);
		member.setPassword(StringUtil.md5(password));
		member.setReal_name(real_name);

		// 设置年级
		char one = student_number.charAt(1);
		char second = student_number.charAt(2);
		member.setGrade("20" + one + second + "级");

		// 设置默认头像
		member.setPicture("fs:/images/default.gif");

		member.setNick_name(nick_name);
		member.setWeb_lvid(1);
		member.setPoint(0);
		member.setPublish(0);
		member.setSign_in(0);
		member.setIs_activation(1);

		Date date = new Date();
		member.setCreate_time(date.getTime() / 1000);

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");

		String ym = format.format(date);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(ym, "0");
		member.setLogincount(JsonUtil.MapToJson(map));

		try {

			this.memberManager.registor(member);

			// 放入session
			HttpServletRequest request = ThreadContextHolder.getHttpRequest();
			HttpSession session = request.getSession();

			// 修改登录次数和登录时间
			Member member2 = this.memberManager
					.findByStudentNumber(student_number);

			map.put(ym, "1");
			Date date2 = new Date();
			this.memberManager.logincountAndlast(member2.getMember_id(),
					JsonUtil.MapToJson(map), date2.getTime() / 1000);

			member2.setLogincount(JsonUtil.MapToJson(map));
			member2.setLastlogin(date2.getTime() / 1000);
			session.setAttribute("member", member2);

			return JsonResultUtil.getSuccessJson("注册成功！");

		} catch (Exception e) {
			e.printStackTrace();
			return JsonResultUtil.getErrorJson("注册失败！");
		}

	}

	/**
	 * 
	 * @function 检测学号是否注册过
	 * @param student_number
	 *            ----学号
	 * @return :消息
	 */
	@ResponseBody
	@RequestMapping(value = "/check-student_number")
	public JsonResult checkStudentNumber(String student_number,
			Integer member_id) {

		student_number = student_number.toUpperCase();
		if (member_id != null) {

			Member member = this.memberManager.findById(member_id);
			if (member == null) {
				return JsonResultUtil.getErrorJson("未知错误！");
			}
			if (member.getStudent_number().equals(student_number)) {
				return JsonResultUtil.getSuccessJson("ok！");
			}

		}

		int count = this.memberManager.checkIsRegister(student_number);
		if (count == 0) {
			if (member_id != null) {
				return JsonResultUtil.getSuccessJson("可以修改！");
			}
			return JsonResultUtil.getSuccessJson("可以注册！");
		}

		return JsonResultUtil.getErrorJson("已经注册过了！");
	}

	/**
	 * 
	 * @function 检测昵称是否注册过
	 * @param nick_name
	 *            ----昵称
	 * @return :消息
	 */
	@ResponseBody
	@RequestMapping(value = "/check-nick_name")
	public JsonResult checkNickName(String nick_name, Integer member_id) {

		if (member_id != null) {

			Member member = this.memberManager.findById(member_id);
			if (member == null) {
				return JsonResultUtil.getErrorJson("未知错误！");
			}
			if (member.getNick_name().equals(nick_name)) {
				return JsonResultUtil.getSuccessJson("ok！");
			}

		}

		int flag = this.memberManager.checkNickName(nick_name);
		if (flag == 0) {
			if (member_id != null) {
				return JsonResultUtil.getSuccessJson("可以修改！");
			}
			return JsonResultUtil.getSuccessJson("可以注册！");
		}
		return JsonResultUtil.getErrorJson("已经注册过了！");
	}

	/**
	 * 
	 * @function 安全退出
	 * @return :消息
	 */
	@ResponseBody
	@RequestMapping(value = "/logout")
	public JsonResult logout() {

		HttpServletRequest request = ThreadContextHolder.getHttpRequest();
		HttpSession session = request.getSession();
		try {
			Member member = (Member) session.getAttribute("member");
			session.removeAttribute("member");

			return JsonResultUtil.getSuccessJson("退出成功！");
		} catch (Exception e) {
			e.printStackTrace();
			return JsonResultUtil.getErrorJson("退出失败！请重试！");
		}
	}

	/**
	 * 
	 * @function 登录
	 * @param student_number
	 *            ----学号
	 * @param password
	 *            ----密码
	 * @return :消息
	 */
	@ResponseBody
	@RequestMapping("/login")
	public JsonResult login(String student_number, String password) {

		if (student_number == null) {
			return JsonResultUtil.getErrorJson("请求错误！学号没有填写！");
		}
		if (student_number.equals("")) {
			return JsonResultUtil.getErrorJson("请求错误！学号没有填写！");
		}
		if (password == null) {
			return JsonResultUtil.getErrorJson("请求错误！密码没有填写！");
		}
		if (password.equals("")) {
			return JsonResultUtil.getErrorJson("请求错误！密码没有填写！");
		}

		student_number = student_number.toUpperCase();
		// 学号验证
		if (!student_number.startsWith("P1")) {
			return JsonResultUtil.getErrorJson("请求错误！学号填写错误！");
		}
		if (student_number.length() != 10) {
			return JsonResultUtil.getErrorJson("请求错误！学号填写错误！");
		}

		// 判断密码是否符合规则
		if (password.length() < 6 || password.length() > 12) {
			return JsonResultUtil.getErrorJson("请求错误！密码填写不争取！");
		}

		// 判断是否正确
		Member member = this.memberManager.findByStudentNumberAndPassword(
				student_number, password);
		if (member == null) {
			return JsonResultUtil.getErrorJson("用户名或密码错误！");
		}

		HttpServletRequest request = ThreadContextHolder.getHttpRequest();

		// 加入session
		HttpSession session = request.getSession();
		// 修改登录次数和登录时间
		String logincount = member.getLogincount();
		Map<String, Object> loginMap = JsonUtil.toMap(logincount);
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		String ym = format.format(date);
		String countstring = (String) loginMap.get(ym);
		if (countstring != null) {
			Integer count = Integer.parseInt(countstring);
			loginMap.put(ym, count + 1 + "");
		} else {
			loginMap.put(ym, "1");
		}
		this.memberManager.logincountAndlast(member.getMember_id(),
				JsonUtil.MapToJson(loginMap), date.getTime() / 1000);

		member.setLogincount(JsonUtil.MapToJson(loginMap));
		member.setLastlogin(date.getTime() / 1000);
		session.setAttribute("member", member);

		return JsonResultUtil.getSuccessJson("登录成功！");
	}

}
